package org.abratuhi.kvngroupware.team.mptua;

import java.util.List;
import java.util.Properties;

import org.abratuhi.kvngroupware.login.manager.LoginManager;
import org.abratuhi.kvngroupware.network.AbstractResponseMessageProceeder;
import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.team.manager.TeamManager;
import org.abratuhi.kvngroupware.team.model.Team;
import org.jdom.Element;

public class TeamResponseMessageProceeder extends AbstractResponseMessageProceeder{
	LoginManager loginmanager;
	TeamManager teammanager;

	public TeamResponseMessageProceeder(MessageSender sender, Properties locale, LoginManager loginmanager, TeamManager teammanager){
		super(sender, locale);
		this.loginmanager = loginmanager;
		this.teammanager = teammanager;
	}

	@Override
	public void proceedMessage(Client client, Message message) {
		Element response = ((Element) message.getRoot().getChildren("response").get(0));
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");
		
		if(type.equals("team")){
			String status = response.getAttributeValue("status");
			Team t = Team.fromElement(response.getChild("team"));

			if(status.equals("ok")){
				if(action.equals("create")){
					teammanager.put(t.getId(), t);
				}
				else if(action.equals("get")){
					List<Element> teams = response.getChildren("team");
					teammanager.clear();
					for(int i=0; i<teams.size(); i++){
						Team team = Team.fromElement(teams.get(i));
						teammanager.put(team.getId(), team);
					}
				}
				else if(action.equals("update")){
					teammanager.update(t.getId(), t);
				}
				else if(action.equals("delete")){
					teammanager.remove(t.getId());
				}
			}
		}
	}

}
